<?php
namespace Mobile\Controller;

use Mobile\Model\tmpmsgModel;
use Mobile\Controller\WechatController;
use Think\Controller;

class BackopenController extends Controller
{

    public $tmpmsgModel;

    public $Wechatobj;
    
    // 初始化连接微信
    public function __construct()
    {
        // parent::__construct();
        $this->tmpmsgModel = new tmpmsgModel();
        $this->Wechatobj = new WechatController();
    }
    
    // 模板消息测试
    // 定时发送模板消息
    public function index()
    {
        $id = get("id");
        
        $where_msg = array(
            "id" => $id
        );
        
        $msg = $this->tmpmsgModel->where($where_msg)->find(); // 取出数据
        
        if (empty($msg)) {
            return_json(0, "DATA_EMPTY");
        }
        
        // 发送消息
        $total = 1; // 总的条数
        $success_nums = 0;
        
        $openid = $msg['openid'];
        if (! $openid) {
            // 关闭空数据
            $this->tmpmsgModel->where(array(
                'id' => $msg['id']
            ))->setField('status', 4); // 假删除
            return_json(0, "DATA_EMPTY");
        }
        
        $content = $msg['content'];
        // 发送模板消息
        // 判断发送时间
        if ($msg['send_plan_time'] > time() || ($msg['status'] > 0)) {
            return_json(0, "DATA_EMPTY");
        }
        
        // 正在发送
        $data = array(
            'send_time' => time(),
            'status' => 3
        );
        
        $res = $this->tmpmsgModel->edittmpmsg($where_msg, $data);
        
        $res = $this->Wechatobj->sendTemplateMessage($content);
        
        if (isset($res['errcode']) && ($res['errcode'] == 0)) {
            // 发送成功
            $data = array(
                'send_time' => time(),
                'status' => 1,
                'errmsg' => $res['errmsg']
            );
            $res = $this->tmpmsgModel->edittmpmsg($where_msg, $data);
            
            // $res = $this->tmpmsgModel->where($where_msg)->delete();
            if ($res) {
                $success_nums ++;
            }
        } else {
            // 发送失败
            $data = array(
                'send_time' => time(),
                'status' => 2,
                'errmsg' => $res['errmsg']
            );
            if ($res['errcode'] == '40001') {
                $data['status'] = - 1;
            }
            $this->tmpmsgModel->edittmpmsg($where_msg, $data);
        }
        
        $return = array(
            "success" => $success_nums,
            "total" => $total
        );
        
        return_json(0, "SUCCESS", $return);
    }
}